package com.zys.el.user.util.BaiduApi;


import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

public class TextSimilar {


    public static final String API_KEY = "s4vXElI3UYKPmKGLQTY8AgkY";
    public static final String SECRET_KEY = "G5g8egQin6nbjqGZU8DV7HTaN1ElUXUT";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public String result(String word1, String word2) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"text_1\":\" " + word1 + "\"," +
                "\"text_2\":\"" + word2 + "\"}");

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/nlp/v2/simnet?charset=UTF-8&access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        return response.body().string();
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return (String) JSONObject.parseObject(response.body().string()).get("access_token");
    }


    public static void main(String[] args) throws IOException {
        TextSimilar t = new TextSimilar();
        String result = t.result("会计", "金融工程");
        System.out.println(result);
    }
}
